package com.ofood.springcloud.service.impl;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.ofood.springcloud.dao.FoodDao;
import com.ofood.springcloud.domain.Food;
import com.ofood.springcloud.service.IFoodService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class FoodServiceImpl implements IFoodService {
    @Resource
    FoodDao foodDao;

    @Override
    public int create(Food food) {
        return foodDao.create(food);
    }

    @Override
    public Food getFoodById(long foodId) {
        return foodDao.getFoodById(foodId);
    }

    @Override
    @HystrixCommand(fallbackMethod = "fallbackTimeout", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public String getFoodTimeout() {
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "no time out";
    }

    @Override
    @HystrixCommand(fallbackMethod = "fallbackError", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")
    })
    public String getFoodError() {
        int a = 5 / 0;
        return "error";
    }

    //=====服务熔断
    @HystrixCommand(fallbackMethod = "foodCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少后跳闸
    })
    public String foodCircuitBreaker(Integer id)
    {
        if(id < 0)
        {
            throw new RuntimeException("******id 不能负数");
        }
        String serialNumber = UUID.randomUUID().toString();

        return Thread.currentThread().getName()+"\t"+"调用成功，流水号: " + serialNumber;
    }

    public String foodCircuitBreaker_fallback(Integer id)
    {
        return "id 不能负数，请稍后再试，/(ㄒoㄒ)/~~   id: " +id;
    }

    public String fallbackTimeout() {
        return "哈哈哈，超时了！";
    }

    public String fallbackError() {
        return "哈哈哈，报异常了！";
    }
}
